package com.itheima.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.CustomException;
import com.itheima.common.R;
import com.itheima.common.ThreadLocalUtil;
import com.itheima.entity.*;
import com.itheima.mapper.OrderDetailMapper;
import com.itheima.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserService userService;
    /**
     * 生成订单
     * @param order
     * @return
     */
    @PostMapping("/submit")
    @Transactional
    public R addOrder(@RequestBody Orders order){
        log.info("orders:{}",order);//可获取addressBookId,payMethod,remark
        //获取购物车信息
        Long userId = ThreadLocalUtil.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lqw=new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(lqw);
        if(shoppingCarts==null || shoppingCarts.size()==0){
            throw new CustomException("购物车为空，不能下单");
        }
       //生成订单号(雪花算法)
        long orderId = IdWorker.getId();//订单号对应order表中的number
        //实收金额 amount
        BigDecimal amount=new BigDecimal(0);//总金额
        //orderdetails表的数据添加
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orderId);//设置订单号
            //计算金额
            BigDecimal price = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
            orderDetail.setAmount(price.multiply(number));
            amount=amount.add(orderDetail.getAmount());
            orderDetailMapper.insert(orderDetail);
        }
        log.info("amount:{}",amount);

        //orders表的数据添加
        //获取用户信息
        User user = userService.getById(userId);
        //获取默认地址信息
        AddressBook address= addressBookService.getById(order.getAddressBookId());
        if(address==null){
            throw new CustomException("用户地址信息有误，不能下单");
        }
       //保存订单信息
        order.setId(orderId);
        order.setNumber(String.valueOf(orderId));
        order.setStatus(2);
        order.setUserId(userId);
        order.setUserName(user.getName());
        order.setConsignee(address.getConsignee());
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        order.setPhone(address.getPhone());
        order.setAmount(amount);
        order.setAddress((address.getProvinceName()==null?"":address.getProvinceName())+
                        (address.getCityName()==null?"":address.getCityName())+
                        (address.getDistrictName()==null?"":address.getDistrictName())+
                        (address.getDetail()==null?"":address.getDetail()));
        orderService.save(order);
        //清空购物车数据
        LambdaQueryWrapper<ShoppingCart> lqws=new LambdaQueryWrapper<>();
        lqws.eq(ShoppingCart::getUserId,userId);
        shoppingCartService.remove(lqws);
        return R.success("生成订单成功");
    }

    /**
     * 查看历史订单
     * @param
     * @param
     * @return
     */
    @GetMapping("/userPage")
    public R orderPaging(int page,int pageSize){
        log.info("page:{},pageSize:{}",page,pageSize);
        Page<Orders> pageInfor=new Page<>(page,pageSize);
        orderService.page(pageInfor);
        log.info("pageInfor:{}",pageInfor);
        return R.success(pageInfor);
    }

    /**
     * 订单明细查询
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R pageQuery(int page,int pageSize,String number,String beginTime,String endTime){

        log.info("beginTime:{}",beginTime);
        Page<Orders> pageInfor=new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> lqw=new LambdaQueryWrapper<>();
        lqw.eq(number!=null,Orders::getNumber,number);
        if(beginTime!=null&&endTime!=null){
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime.parse(beginTime,df);
            LocalDateTime.parse(endTime,df);
            lqw.between(beginTime!=null&&endTime!=null,
                    Orders::getOrderTime,beginTime,endTime);
        }



        //String转LocalDateTime

        lqw.orderByAsc(Orders::getOrderTime);
        orderService.page(pageInfor,lqw);
        return R.success(pageInfor);
    }


    // 取消，派送，完成接口
    @PutMapping
    public R  editOrderDetail(@RequestBody Orders order){
        log.info("order:{}",order);
        LambdaUpdateWrapper<Orders> luw=new LambdaUpdateWrapper<>();
        luw.set(Orders::getStatus,order.getStatus());
        orderService.update(luw);
        return R.success("派单成功");
    }

    //导出excel
    @GetMapping("/export")
    public void exportOrders(HttpServletResponse response) throws IOException {
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String fileName= URLEncoder.encode("订单明细表","UTF-8");
            response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx");
            List<Orders> orders = orderService.list();
            ServletOutputStream outputStream = response.getOutputStream();
            EasyExcel.write(outputStream,Orders.class).sheet("订单明细表").doWrite(orders);
            outputStream.close();
    }


}
